package com.zyl.blog.common.utils.Extreme;

import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog
 * @Package: com.zyl.common.utils.Extreme
 * @ClassName: CronToDurationParser
 * @Description:
 * @Author FinalFantasy
 * @Date 2025/3/26-21:49
 */
public class CronToDurationParser {

    public static String parseFixedDuration(String cronExpression) {
        String[] fields = cronExpression.split("\\s+");

        // 按字段优先级顺序检查间隔（秒 > 分钟 > 小时 > 日）
        for (int i = 0; i < 4; i++) {
            String field = fields[i];
            if (field.startsWith("*/")) {
                int interval = parseInterval(field);
                if (interval > 0) {
                    return buildISODuration(i, interval);
                }
            }
        }
        throw new IllegalArgumentException("未找到有效的间隔配置: " + cronExpression);
    }

    private static int parseInterval(String field) {
        Pattern pattern = Pattern.compile("\\*/(\\d+)");
        Matcher matcher = pattern.matcher(field);
        if (matcher.find()) {
            return Integer.parseInt(matcher.group(1));
        }
        return -1;
    }

    private static String buildISODuration(int fieldIndex, int interval) {
        return switch (fieldIndex) {
            case 0 -> // 秒
                    Duration.ofSeconds(interval).toString();
            case 1 -> // 分钟
                    Duration.ofMinutes(interval).toString();
            case 2 -> // 小时
                    Duration.ofHours(interval).toString();
            case 3 -> // 天
                    "P" + interval + "D";
            default -> throw new IllegalArgumentException("无效的字段位置");
        };
    }
}
